package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送手机验证码
     *
     * @param phone
     * @param session
     */
    public Result sendCode(String phone, HttpSession session) {
        //校验手机号
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(phone);

        //不合格，返回错误
        if (phoneInvalid) {
            return Result.fail("手机号不正确！");
        }

        //合格，生成验证码
        String code = RandomUtil.randomNumbers(6);

        //将验证码保存在redis里
        String key = RedisConstants.LOGIN_CODE_KEY + phone;
        stringRedisTemplate.opsForValue().set(key, code);
        stringRedisTemplate.expire(key,RedisConstants.LOGIN_CODE_TTL,TimeUnit.MINUTES);//设置验证码有效期2分钟

        //发送验证码
        log.info("发送验证码成功，{}", code);

        //返回成功信息
        return Result.ok();

    }

    /**
     * 登录功能,只校验验证码登录
     *
     * @param loginForm
     * @param session
     * @return
     */
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.检验手机号 true---无效手机号   false---有效手机号
        String phone = loginForm.getPhone();
        boolean phoneInvalid = RegexUtils.isPhoneInvalid(phone);
        if (phoneInvalid) {
            return Result.fail("手机号不正确！");
        }

        //2.校验验证码登录
        String code = loginForm.getCode();
        String redisCode = stringRedisTemplate.opsForValue()
                .get(LOGIN_CODE_KEY + phone); //redis的验证码
        log.info("验证码redisCode为：{}", redisCode);

        //3.验证码不存在，或错误
        if (code == null || !code.equals(redisCode)) {
            log.info("验证码错误");
            return Result.fail("验证码错误");
        }

        //3.验证码存在，且正确，查找redis数据库是否有这个用户
        User user = query().eq("phone", phone).one();
        if (user == null) {
            //4.数据库没有这个用户，直接创建这个用户
            user = createUser(phone);
        }
        //5.将用户保存在redis里
        String token = LOGIN_USER_KEY + UUID.randomUUID();
        log.info("token为：{}",token);

        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO);

        //map里的数据要转为String
        Map<String, String> hsahMap = new HashMap<>();
        userMap.forEach((k, v) -> hsahMap.put(k, v != null ? v.toString() : ""));

        stringRedisTemplate.opsForHash().putAll(token,hsahMap);
        stringRedisTemplate.expire(token,LOGIN_USER_TTL, TimeUnit.MINUTES);//为key设置有效期30分钟

        //6.返回token
        return Result.ok(token);
    }

    private User createUser(String phone) {
        //创建用户
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + "---" + RandomUtil.randomString(10));
        //添加
        save(user);
        return user;

    }
}
